<template>
  <div class="d-flex vh-100 justify-content-center align-items-center bg-light">
    <div class="card p-4 shadow" style="min-width: 320px; max-width: 400px; width: 100%">
      <h3 class="text-center mb-4">管理端登录</h3>
      <div class="mb-3">
        <label class="form-label">用户名</label>
        <input v-model="username" type="text" class="form-control" placeholder="请输入用户名" />
      </div>

      <div class="mb-3">
        <label class="form-label">密码</label>
        <input v-model="password" type="password" class="form-control" placeholder="请输入密码" />
      </div>

      <button class="btn btn-primary w-100" @click="login">登录</button>

      <div v-if="error" class="alert alert-danger mt-3 p-2 text-center">
        {{ error }}
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import axios from "axios";
import { useRouter } from "vue-router";
import { useUserStore } from "@/stores/modules/user.ts";

const userStore = useUserStore();
const router = useRouter();
const username = ref("");
const password = ref("");
const error = ref("");

async function login() {
  error.value = "";
  if (!username.value || !password.value) {
    error.value = "用户名和密码不能为空";
    return;
  }
  try {
    const res = await axios.post("/admin/login", {
      username: username.value,
      password: password.value
    });

    // 假设返回 JWT token
    if (res.data.code === 1000) {
      userStore.setToken(res.data.data);
      router.push("/admin/rooms");
    } else {
      error.value = res.data.msg;
    }
  } catch (e) {
    error.value = e.response?.data?.msg || "登录失败";
  }
}
</script>

<style scoped>
body {
  margin: 0;
}
</style>
